package cn.sinjet.myview;

import com.mgroup.wazehelper.R;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class ScanCarView extends ImageView{
    Context context;
    ValueAnimator animator;
    Drawable scanner;
    Bitmap bmScanner;
    float maxRange = 250.0f;
    float scannerHeight = 50.0f;
	public ScanCarView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.context = context;
		try{
			TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.ScancarView);
			scanner = typedArray.getDrawable(R.styleable.ScancarView_scanner_image);
			maxRange = typedArray.getDimension(R.styleable.ScancarView_scan_max_range, 250.0f);
			scannerHeight = typedArray.getDimension(R.styleable.ScancarView_scanner_height, 50.0f);
			typedArray.recycle();
			Log.d("draw","px");
		}catch(OutOfMemoryError err){
			err.printStackTrace();
		    System.gc();
		}
		
		animator = ValueAnimator.ofFloat(0,maxRange);
		animator.setDuration(1500);
		animator.setRepeatMode(ValueAnimator.REVERSE);
		animator.setRepeatCount(ValueAnimator.INFINITE);
	}
	
	Paint paint = null;
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		if(paint == null) paint = new Paint();
		if(bmScanner == null && scanner != null){
	    	   Bitmap bmBg = ((BitmapDrawable)scanner).getBitmap();
				try{
					bmScanner = Bitmap.createScaledBitmap(bmBg, getWidth(), (int)scannerHeight, false);
				}catch(Exception e){
					e.printStackTrace();
					System.gc();
				}
	    	}
		if(animator.isRunning()){
			canvas.translate(0.0f, (Float)animator.getAnimatedValue());
			canvas.drawBitmap(bmScanner, 0, 0, paint);
			invalidate();
		}
	}

	public void setScanning(int scanning){
		if(scanning == 1){
		    animator.start();
		    invalidate();
		}else{
			animator.end();
			invalidate();
		}
	}
}
